package com.cmccsi.uc;

import java.io.File;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import com.cmccsi.entity.ComparatorQxDeptEx;
import com.cmccsi.entity.ComparatorQxDeptMemberEx;
import com.cmccsi.entity.ComparatorQxDomianEx;
import com.cmccsi.entity.ComparatorQxUserEx;
import com.cmccsi.entity.qxdeptDto;
import com.cmccsi.entity.qxdeptDtoEx;
import com.cmccsi.entity.qxdeptMemberDto;
import com.cmccsi.entity.qxdeptMemberDtoEx;
import com.cmccsi.entity.qxdomainDto;
import com.cmccsi.entity.qxdomainDtoEx;
import com.cmccsi.entity.qxuserDto;
import com.cmccsi.entity.qxuserDtoEx;
import com.cmccsi.service.UserService;
import com.cmccsi.service.impl.DeptMemberServiceImpl;
import com.cmccsi.service.impl.DeptServiceImpl;
import com.cmccsi.service.impl.DomainServiceImpl;
import com.cmccsi.service.impl.QxUserServiceImpl;
import com.cmccsi.service.impl.UserServiceImpl;
import com.cmccsi.utils.FTPUtil;
import com.cmccsi.utils.FileOperate;
import com.cmccsi.utils.IFileOperate;
import com.cmccsi.utils.MD5;

public class SynChrData implements ISynChrData {

	private String ftpserver;
	private String userLogin;
	private String pwdLogin;
	private String serverPath;

	private String strTodayFolderName = "";// 今天的文件夹yyyyMMdd

	private String strfileNames = "";// 文件名字通配符 yyMMdd

	private String strDeptFileEx = "DEPTINFOTB";// 文件开始文件名
	private String strUserFileEx = "PHONEINFOTB";// 文件开始文件名
	private String strDomainFileEx = "TBECINFO";// 文件开始文件名
	private String DataFileEncode = "UTF-8";

	private String strDeptFileContent = "";
	private String strUserFileContent = "";
	private String strDomainFileContent = "";

	private String strDataDir = "DataFiles";

	private List<qxdomainDtoEx> lstdomainDatas = new ArrayList<qxdomainDtoEx>();
	private List<qxdeptDtoEx> lstdeptDatas = new ArrayList<qxdeptDtoEx>();
	private List<qxuserDtoEx> lstuserDatas = new ArrayList<qxuserDtoEx>();
	private List<qxdeptMemberDtoEx> lstdptMemberDatas = new ArrayList<qxdeptMemberDtoEx>();
	
	
	private Logger loger = Logger.getLogger(SynChrData.class);

	public SynChrData() {
		ResourceBundle resource = ResourceBundle.getBundle("ftp");
		ftpserver = resource.getString("ftpserver");
		userLogin = resource.getString("userLogin");
		pwdLogin = resource.getString("pwdLogin");
		serverPath = resource.getString("serverPath");
	}
	
	
	private void initData()	
	{
		
		strTodayFolderName = "";// 今天的文件夹yyyyMMdd
		strfileNames = "";// 文件名字通配符 yyMMdd
		strDeptFileContent = "";
		strUserFileContent = "";
		strDomainFileContent = "";	
		lstdomainDatas = new ArrayList<qxdomainDtoEx>();
		lstdeptDatas = new ArrayList<qxdeptDtoEx>();
		lstuserDatas = new ArrayList<qxuserDtoEx>();
		lstdptMemberDatas = new ArrayList<qxdeptMemberDtoEx>();
		
	}
	
	

	public void GoSynChrData()

	{
		try {
			
			//初始化
			loger.error("initData()");
			initData();
			// 从FTP下载文件
			loger.error("GetFtpDataFiles()");
			GetFtpDataFiles();
			// 分析已经下载的文件 将文件的数据写入数据库
			loger.error("AnalyseDataFilesAndWirteData()");
			AnalyseDataFilesAndWirteData();

		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}
	}

	@Override
	public void GetFtpDataFiles() {
		try {
			File directory = new File("");
			String strCurrDir = directory.getCanonicalPath();
			strTodayFolderName = "";
			FTPUtil ftp = new FTPUtil();
			IFileOperate fileOPr = new FileOperate();
			fileOPr.createFolder(strDataDir);
			// 创建今天的文件夹
			SimpleDateFormat formatterFolder = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat formatterFile = new SimpleDateFormat("yyMMdd");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			strTodayFolderName = strCurrDir + File.separator + strDataDir
					+ File.separator + formatterFolder.format(curDate);
			strfileNames = formatterFile.format(curDate);

			fileOPr.createFolder(strTodayFolderName);
			// 把读取到的文件全部放到今天的文件夹内
			ftp.downFile(ftpserver, 21, userLogin, pwdLogin, serverPath,
					strfileNames, strTodayFolderName, true);

		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}

	}

	@Override
	public void AnalyseDataFilesAndWirteData() {
		// TODO Auto-generated method stub
		try {

			IFileOperate fileOPr = new FileOperate();
			// 读取今天文件夹内的文件的内容到内存
			File[] files = fileOPr.getFileList(strTodayFolderName);

			for (File file : files) {

				if (file.getName().startsWith(strDeptFileEx)) {
					if(strDeptFileContent!="")
					{
						strDeptFileContent+="\n";
					}
					strDeptFileContent += fileOPr.readTxt(
							file.getAbsolutePath(), DataFileEncode);					
					
				}

				else if (file.getName().startsWith(strUserFileEx)) {
					if(strUserFileContent!="")
					{
						strUserFileContent+="\n";
					}
					strUserFileContent += fileOPr.readTxt(
							file.getAbsolutePath(), DataFileEncode);
				}

				else if (file.getName().startsWith(strDomainFileEx)) {
					if(strDomainFileContent!="")
					{
						strDomainFileContent+="\n";
					}
					strDomainFileContent += fileOPr.readTxt(
							file.getAbsolutePath(), DataFileEncode);
				}

			}

			// 将公司数据、部门数据、人员数据插入的数据库中，注意三者的顺序不能变，否则有问题

			if (!strDomainFileContent.isEmpty()) {
				String[] domainDatas = strDomainFileContent.split("\n");
				if (domainDatas != null && domainDatas.length > 0) {
					for (String domain : domainDatas) {
						
						try {
							if(domain.isEmpty()||domain=="")
							{
								continue;
							}
							loger.error("domain Data:" + domain);
							String[] singaldomainDatas = domain.split(",");
							qxdomainDtoEx qxdomainEx = new qxdomainDtoEx();
							qxdomainDto qxdomain = new qxdomainDto();

							qxdomain.setDomainName(singaldomainDatas[0]);
							qxdomain.setEccode(singaldomainDatas[1]);
							qxdomainEx.setQxDomain(qxdomain);
							qxdomainEx.setStatus(Integer
									.parseInt(singaldomainDatas[3]));
							lstdomainDatas.add(qxdomainEx);
						} catch (Exception e) {
							// TODO: handle exception
							loger.error(e.getMessage(), e);
						}

					}
				}

			}

			WriteDmoainDataToDB();

			DomainServiceImpl domaSrv = new DomainServiceImpl();
			List<qxdomainDto> domains = domaSrv.findAll();
			Map<String, qxdomainDto> domainsMap = new HashMap<String, qxdomainDto>();
			for (qxdomainDto _domian : domains) {
				String eccode = _domian.getEccode();
				if (!domainsMap.containsKey(eccode)) {
					domainsMap.put(eccode, _domian);
				}
			}		
			
			DeptServiceImpl dptSrv = new DeptServiceImpl();
			List<qxdeptDto> depts = dptSrv.findAllRootDepts();
			Map<String, qxdeptDto> deptsMap = new HashMap<String, qxdeptDto>();
			for (qxdeptDto _dpt : depts) {
				String domainid = _dpt.getDomainid();
				if (!deptsMap.containsKey(domainid)) {
					deptsMap.put(domainid, _dpt);
				}
			}
			
			

			if (!strUserFileContent.isEmpty()) {
				String[] userDatas = strUserFileContent.split("\n");
				if (userDatas != null && userDatas.length > 0) {
					String defaultPWd = MD5.MD5Encode("123456");// 默认密码
					for (String user : userDatas) {
						try {
							if(user.isEmpty()||user=="")
							{
								continue;
							}
							loger.error("user Data:" + user);
							String[] singaluserDatas = user.split(",");
							qxuserDtoEx qxuserEx = new qxuserDtoEx();
							qxuserDto qxuser = new qxuserDto();

							qxdeptMemberDtoEx qxdptMemberEx = new qxdeptMemberDtoEx();
							qxdeptMemberDto qxdptMember = new qxdeptMemberDto();

							qxuser.setId(Long.parseLong(singaluserDatas[0]));
							qxuser.setDisplayName(singaluserDatas[1]);
							loger.error("处理的用户名：" + singaluserDatas[1]
									+ ",用户ID：" + singaluserDatas[0]);
							Boolean gender = false;
							if (Integer.parseInt(singaluserDatas[2]) == 1) {
								gender = true;
							}
							qxuser.setGender(gender);
							qxuser.setMobilePhone(singaluserDatas[3]);
							qxuser.setUserName(singaluserDatas[3]);
							qxuser.setEmail(singaluserDatas[4]);
							qxuser.setFax(singaluserDatas[5]);
							qxuser.setOfficePhone(singaluserDatas[6]);
							qxuser.setOfficeExten(singaluserDatas[7]);
							qxdomainDto dptdomain = domainsMap
									.get(singaluserDatas[8]);
							if (dptdomain != null) {
								qxuser.setDomainid(dptdomain.getDomain());
							} else {
								loger.error("用户：" + qxuser.getDisplayName()
										+ "对应的企业ID有误，企业ID："
										+ singaluserDatas[8]);
								continue;
							}

							if (singaluserDatas[9] == null
									|| singaluserDatas[9].isEmpty()) {
								qxdptMember.setDeptId((long) 0);
							} else {
								
								qxdptMember.setUserId(qxuser.getId());
								
//								Long deptId=Long
//										.parseLong(singaluserDatas[9]);
								String strDeptid= singaluserDatas[9];
								if(strDeptid==null||strDeptid.isEmpty())
								{
									strDeptid="0";
								}
								
								Long deptId=Long
										.parseLong(strDeptid);
								
								if(deptId==0)
								{
									//处理部门id为0时的特殊情况
									qxdeptDto dept=deptsMap.get(qxuser.getDomainid());
									qxdptMember.setDeptId(dept.getId());
								}
								else
								{
									qxdptMember.setDeptId(deptId);
								}
								
								
								qxdptMember.setTitle(singaluserDatas[10]);
								qxdptMember.setSort(Integer
										.parseInt(singaluserDatas[12]));
								qxdptMember.setStatus(1);
								qxdptMemberEx.setQxDeptMember(qxdptMember);
								qxdptMemberEx.setStatus(Integer
										.parseInt(singaluserDatas[13]));
								lstdptMemberDatas.add(qxdptMemberEx);
							}
							qxuser.setSipExten(singaluserDatas[11]);
							DateFormat fmt = new SimpleDateFormat(
									"MM/dd/yyyy HH:mm:ss");
							Date date = fmt.parse(singaluserDatas[14]);
							qxuser.setCreateTime(date);
							
							//qxuser.setAuth(defaultPWd);
							
							String domainid=qxuser.getDomainid();
							String userPWd = MD5.MD5Encode(domainid);	
							
							qxuser.setAuth(userPWd);							
							
							qxuserEx.setuserDto(qxuser);
							loger.error("user Status:singaluserDatas[13]"
									+ singaluserDatas[13]);
							qxuserEx.setStatus(Integer
									.parseInt(singaluserDatas[13]));
							lstuserDatas.add(qxuserEx);

						} catch (Exception e) {
							// TODO: handle exception
							loger.error(e.getMessage(), e);
						}
					}
				}
			}
			WriteUserDataToDB();

			if (!strDeptFileContent.isEmpty()) {
				String[] deptDatas = strDeptFileContent.split("\n");
				if (deptDatas != null && deptDatas.length > 0) {
					for (String dept : deptDatas) {

						try {
							if(dept.isEmpty()||dept=="")
							{
								continue;
							}
							loger.error("dept Data:" + dept);
							String[] singaldeptDatas = dept.split(",");
							qxdeptDtoEx qxdeptEx = new qxdeptDtoEx();

							qxdeptDto qxdept = new qxdeptDto();
							qxdept.setId(Long.parseLong(singaldeptDatas[0]));
							qxdept.setName(singaldeptDatas[1]);
							
							
													

							qxdomainDto dptdomain = domainsMap
									.get(singaldeptDatas[3]);
							if (dptdomain != null) {
								qxdept.setDomainid(dptdomain.getDomain());
							} else {
								loger.error("部门：" + qxdept.getName()
										+ "对应的企业ID有误，企业ID："
										+ singaldeptDatas[3]);
								continue;
							}
							
//							Long partdeptId=Long
//									.parseLong(singaldeptDatas[2]);	
							
							String strPart= singaldeptDatas[2];
							if(strPart==null||strPart.isEmpty())
							{
								strPart="0";
							}
							Long partdeptId=Long
									.parseLong(strPart);
							
							if(partdeptId==0)
							{
								//处理部门id为0时的特殊情况 
								//查询触发器生成的部门ID
								qxdeptDto pardept=deptsMap.get(qxdept.getDomainid());
								qxdept.setParentId(pardept.getId());
							}
							else
							{
								qxdept.setParentId(partdeptId);
							}

							qxdept.setSort(Integer.parseInt(singaldeptDatas[4]));
							qxdept.setStatus(1);
							DateFormat fmt = new SimpleDateFormat(
									"MM/dd/yyyy HH:mm:ss");
							Date date = fmt.parse(singaldeptDatas[6]);
							qxdept.setCreateTime(date);
							qxdeptEx.setQxDept(qxdept);
							qxdeptEx.setStatus(Integer
									.parseInt(singaldeptDatas[5]));
							lstdeptDatas.add(qxdeptEx);

						} catch (Exception e) {
							// TODO: handle exception
							loger.error(e.getMessage(), e);
						}
					}
				}
			}
			WriteDeptDataToDB();
		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}
	}

	@Override
	public void WriteDeptDataToDB() {
		// TODO Auto-generated method stub

		try {

			DeptServiceImpl dptSrv = new DeptServiceImpl();
			DeptMemberServiceImpl dptMemberSrv = new DeptMemberServiceImpl();
			ComparatorQxDeptEx cmp=new ComparatorQxDeptEx();
			 Collections.sort(lstdeptDatas,cmp);//排序 先处理insert 后处理update 最后处理delete			
			for (qxdeptDtoEx qxdptEx : lstdeptDatas) {

				switch (qxdptEx.getStatus()) {
				case 1:
					loger.error("save处理的qxdpt deptid：" + qxdptEx.getQxDept().getId()
							+ ",Name：" +qxdptEx.getQxDept().getName());
					dptSrv.save(qxdptEx.getQxDept());
					break;
				case 2:
					loger.error("update处理的qxdpt deptid：" + qxdptEx.getQxDept().getId()
							+ ",Name：" +qxdptEx.getQxDept().getName());
					dptSrv.update(qxdptEx.getQxDept());
					break;
				case 3:
					loger.error("delete处理的qxdpt deptid：" + qxdptEx.getQxDept().getId()
							+ ",Name：" +qxdptEx.getQxDept().getName());
					dptSrv.delete(qxdptEx.getQxDept().getId());
					break;
				}

			}
			ComparatorQxDeptMemberEx cmpMember=new ComparatorQxDeptMemberEx();
			 Collections.sort(lstdptMemberDatas,cmpMember);		//排序 先处理insert 后处理update 最后处理delete		
			for (qxdeptMemberDtoEx qxdptMemberEx : lstdptMemberDatas) {
				switch (qxdptMemberEx.getStatus()) {
				case 1:
					loger.error("save处理的dptMember userid：" + qxdptMemberEx.getQxDeptMember().getUserId()
							+ ",dptMemberID：" +qxdptMemberEx.getQxDeptMember().getDeptId());
					dptMemberSrv.save(qxdptMemberEx.getQxDeptMember());
					break;
				case 2:
					loger.error("update处理的dptMember userid：" + qxdptMemberEx.getQxDeptMember().getUserId()
							+ ",dptMemberID：" +qxdptMemberEx.getQxDeptMember().getDeptId());
					dptMemberSrv.update(qxdptMemberEx.getQxDeptMember());
					break;
				case 3:
					loger.error("delete处理的dptMember userid：" + qxdptMemberEx.getQxDeptMember().getUserId()
							+ ",dptMemberID：" +qxdptMemberEx.getQxDeptMember().getDeptId());
					dptMemberSrv
							.delete(qxdptMemberEx.getQxDeptMember().getId());
					break;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}

	}

	@Override
	public void WriteUserDataToDB() {
		// TODO Auto-generated method stub

		try {

			QxUserServiceImpl qxuserSrv = new QxUserServiceImpl();
			ComparatorQxUserEx cmp=new ComparatorQxUserEx();
			 Collections.sort(lstuserDatas,cmp);//排序 先处理insert 后处理update 最后处理delete	
			for (qxuserDtoEx qxuserEx : lstuserDatas) {
				switch (qxuserEx.getStatus()) {
				case 1:
					loger.error("insert处理的用户名："
							+ qxuserEx.getQxUser().getDisplayName() + ",用户ID："
							+ qxuserEx.getQxUser().getId());
					qxuserSrv.save(qxuserEx.getQxUser(), 0);
					break;
				case 2:
					loger.error("Update处理的用户名："
							+ qxuserEx.getQxUser().getDisplayName() + ",用户ID："
							+ qxuserEx.getQxUser().getId());
					qxuserSrv.update(qxuserEx.getQxUser());
					break;
				case 3:
					loger.error("delete处理的用户名：" + qxuserEx.getQxUser().getDisplayName()
							+ ",用户ID：" + qxuserEx.getQxUser().getId());
					qxuserSrv.delete(qxuserEx.getQxUser().getId());
					break;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}

	}

	@Override
	public void WriteDmoainDataToDB() {
		// TODO Auto-generated method stub

		try {

			DomainServiceImpl domaSrv = new DomainServiceImpl();
			ComparatorQxDomianEx cmp=new ComparatorQxDomianEx();
			 Collections.sort(lstdomainDatas,cmp);
			for (qxdomainDtoEx qxdomainEx : lstdomainDatas) {
				switch (qxdomainEx.getStatus()) {
				case 1:
					domaSrv.save(qxdomainEx.getQxDomian());
					break;
				case 2:
					domaSrv.update(qxdomainEx.getQxDomian());
					break;
				case 3:
					domaSrv.delete(qxdomainEx.getQxDomian().getDomain());
					break;
				}

			}

		} catch (Exception e) {
			// TODO: handle exception
			loger.error(e.getMessage(), e);
		}

	}
}
